<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>div移动优化</title>
		<style type="text/css">
			#box1 {
				width: 100px;
				height: 100px;
				background-color: red;
				/* 开启定位 */
				position: absolute;
			}
		</style>
		<script type="text/javascript">
			window.onload = function() {
				// 定义速度
				var speed = 20;
				// 定义方向
				var direct = 0;
				
				// 定时器只控制方向
				setInterval(function(){
					switch (direct) {
						case 37:
							box1.style.left = box1.offsetLeft - speed + "px";
							break;
						case 38:
							box1.style.top = box1.offsetTop - speed + "px";
							break;
						case 39:
							box1.style.left = box1.offsetLeft + speed + "px";
							break;
						case 40:
							box1.style.top = box1.offsetTop + speed + "px";
							break;
						default:
							break;
					}
				}, 50);
				
				// 键盘按下只控制速度
				var box1 = document.getElementById("box1");
				document.onkeydown = function(event) {
					event = event || window.event;
					// 修改速度
					speed = event.ctrlKey ? 50 : 20;
					// 捕获方向
					direct = event.keyCode;
					return false;
				};
				// 键盘松开清空速度和方向
				document.onkeyup = function(event){
					direct = 0;
				}
			};
		</script>
	</head>
	<body>
		<div id="box1"></div>
	</body>
</html>
